package com.cyz.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.cyz.exception.PasswordErrException;
import com.cyz.exception.UserNoExsitException;
import com.cyz.service.UserService;
import com.cyz.service.impl.UserServiceImpl;
import com.cyz.util.MD5Util;

@Controller
@RequestMapping("/RePassword")
public class RePassword {
	@RequestMapping ("/rePassword")
	public ModelAndView  rePassword( HttpServletRequest request,HttpServletResponse response)
	{
		ModelAndView mv=new ModelAndView();
		mv.setViewName("rePassword");
		mv.addObject("prePage",request.getSession().getAttribute("nowPage"));
		return  mv;
	}
	@RequestMapping("change")
	public void change(HttpServletRequest request,HttpServletResponse response)
	{
		String oldpassword = request.getParameter("oldpassword");
		String password = request.getParameter("password");
		String userName=(String) request.getSession().getAttribute("userName");
		//System.out.println("oldpassword:"+oldpassword);
		//System.out.println("password:"+password);
		//System.out.println("username:"+userName);
		UserService userService = new UserServiceImpl();
		Integer userId=userService.getUserIdByUserName(userName);//获取用户id
	//	System.out.println("userid:"+userId);
		PrintWriter printWriter = null;
		try {
			printWriter = response.getWriter();
		} catch (IOException e2) {
			// TODO Auto-generated catch block
			e2.printStackTrace();
		}
		try {
			userService.validate(userName,oldpassword);
			userService.changePassword(userId,password);
			printWriter.write("{\"res\":\"1\"}");
			
		} catch (UserNoExsitException e) {
			//e.printStackTrace();
			printWriter.write("{\"res\":\"0\"}");
		}catch(PasswordErrException e1) {
			//e1.printStackTrace();
			printWriter.write("{\"res\":\"2\"}");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	

}
